<template>
  <a-card>
    <a-form layout="horizontal" :form="searchForm" @submit="handleSearch" autocomplete="off">
      <a-row type="flex" justify="start" :gutter="15">
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-select :options="distributors" v-decorator="['distributor',{ initialValue: '' }]"/>
          </a-form-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-select :options="pushStatusArr" v-decorator="['pushStatus',{ initialValue: '' }]"/>
          </a-form-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-select :options="pushResultArr" v-decorator="['pushResult',{ initialValue: '' }]"/>
          </a-form-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-select :options="saleStatusArr" v-decorator="['isonline',{ initialValue: '' }]"/>
          </a-form-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-select :options="distributorCityArr" v-decorator="['nocity',{ initialValue: '' }]"/>
          </a-form-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-input v-decorator="['distributorHotelId']" :placeholder="$t('distributor_hotel_id')" :allowClear="true"/>
          </a-form-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form-item>
            <a-space>
              <a-button htmlType="submit" type="primary" icon="search">{{ $t('search') }}</a-button>
              <a-button @click="handleReset">
                {{ $t("reset") }}
              </a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row type="flex" justify="start" :gutter="15">
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-input v-decorator="['hotelId']" :placeholder="$t('hotel_id')" :allowClear="true"/>
          </a-form-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form-item>
            <a-input v-decorator="['hotelName']" :placeholder="$t('hotel_name')" :allowClear="true"/>
          </a-form-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-auto-complete :data-source="countryList" v-decorator="['countryName']" :placeholder="$t('country')" :allowClear="true" :filter-option="filterOption"/>
          </a-form-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-input v-decorator="['cityName']" :placeholder="$t('city')" :allowClear="true"/>
          </a-form-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-select v-decorator="['hotelStar',{ initialValue: '' }]">
              <a-select-option value="">
                {{ $t('hotel_star') }}
              </a-select-option>
              <a-select-option value="0">0 {{ $t('star') }}</a-select-option>
              <a-select-option value="1">1 {{ $t('star') }}</a-select-option>
              <a-select-option value="2">2 {{ $t('star') }}</a-select-option>
              <a-select-option value="3">3 {{ $t('star') }}</a-select-option>
              <a-select-option value="4">4 {{ $t('star') }}</a-select-option>
              <a-select-option value="5">5 {{ $t('star') }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form-item>
            <a-space>
              <a-button type="primary" icon="plus" :disabled="(searchParams.distributor === undefined || searchParams.distributor === '') || selectedRows.length === 0" @click="showSetCityForm">{{ $t('distribution_city') }}</a-button>
              <a-button type="primary" icon="check" :disabled="selectedRows.length === 0" @click="saveSetOnline">{{ $t('online') }}</a-button>
              <a-button type="primary" icon="close" :disabled="selectedRows.length === 0" @click="saveSetOffline">{{ $t('offline') }}</a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <a-table size="middle" :columns="columns" :data-source="data" :pagination="{ showSizeChanger: true, showQuickJumper: true, size:'middle', showTotal:(total, range) => `${range[0]}-${range[1]} / ${total}`, current: pageIndex, pageSize: pageSize, total: total, pageSizeOptions:['10','20','30','50','100','1000','2000'], }" :row-key="record => record.id" :loading="loading" @change="handleTableChange" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
      <template slot="hotelId" slot-scope="text, record">
        <a @click="openHotel(record.hotelId)">{{ record.hotelId }}</a>
      </template>
      <template slot="hotelNameEn" slot-scope="text, record">
        {{ record.hotelNameEn }} <br /> {{ record.hotelNameCn }}
      </template>
      <template slot="hotelAddressEn" slot-scope="text, record">
        {{ record.hotelAddressEn }} <br /> {{ record.hotelAddressCn }}
      </template>
      <template slot="distributor" slot-scope="text, record">
        <a @click="openDistributorHotel(record.distributor, record.hotelId)">{{ text }}</a>
      </template>
      <template slot="distributorHotelId" slot-scope="text, record">
        <a v-if="record.distributor.indexOf('ctrip')>=0 && (text !== undefined && text !== '')" :href='"http://hotels.ctrip.com/international/" + text + ".html?fixsubhotel=T"' target='_blank'>{{text}}</a>
        <a v-else-if="record.distributor.indexOf('alitrip')>=0 && (text !== undefined && text !== '')" :href='"https://hotel.fliggy.com/hotel_detail2.htm?shid=" + text' target='_blank'>{{text}}</a>
        <span v-else>{{text}}</span>
      </template>
      <template slot="distributorCityName" slot-scope="text, record">
        <span v-if="record.distributorCityId !== undefined && record.distributorCityId !== ''">{{ record.distributorCityId }}.{{ record.distributorCityName }}</span>
      </template>
      <template slot="pushStatus" slot-scope="text">
        {{ $t("push_status_arr." + text)}}
      </template>
      <template slot="pushResult" slot-scope="text">
        {{ $t("push_result_arr." + text)}}
      </template>
      <a-icon slot="isonline" slot-scope="text" :type="text?'check-circle':'close-circle'" :style="text?'color:#52c41a;font-size: 18px;':'font-size: 18px;'"/>
      <template v-for="(item, index) in columns" :slot="item.slotName">
        <span :key="index">{{ $t(item.slotName) }}</span>
      </template>
    </a-table>

    <a-modal v-model="setCityFormVisible" :maskClosable="false" :title="$t('distribution_city')" :okText="$t('submit')" @ok="saveSetCityForm()" @cancel="closeSetCityForm()" :confirm-loading="submitLoading">
      <a-form-model ref="updateForm" layout="vertical" :model="cityForm" autocomplete="off" :rules="cityFormRules" >
        <a-form-model-item prop="distributorCityId" :label="$t('distributor_city_name') + 'Code'">
          <a-input v-model="cityForm.distributorCityId">
          </a-input>
        </a-form-model-item>
        <a-form-model-item prop="distributorCityName" :label="$t('distributor_city_name')">
          <a-input v-model="cityForm.distributorCityName">
          </a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

  </a-card>
</template>

<script>
import {getPublicData} from '@/services/public'
import {getHotelList,setCity,setOnline,setOffline} from '@/services/distributor'

export default {
  name: "DistributorHotelList",
  i18n: require('../i18n'),
  data() {
    return {
      distributors: [],
      pushStatusArr: [],
      pushResultArr: [],
      saleStatusArr: [],
      distributorCityArr: [],
      countryList: [],
      searchParams: {},
      searchForm: this.$form.createForm(this, {name: 'search'}),
      pageIndex: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      data: [],
      submitLoading: false,
      columns: [
        {
          dataIndex: 'hotelId',
          align: 'center',
          slotName: "hotel_id",
          slots: {title: 'hotel_id'},
          scopedSlots: {customRender: 'hotelId'},
        },
        {
          dataIndex: 'hotelNameEn',
          align: 'left',
          slotName: "hotel_name",
          slots: {title: 'hotel_name'},
          scopedSlots: {customRender: 'hotelNameEn'},
        },
        {
          dataIndex: 'hotelStar',
          align: 'center',
          slotName: "hotel_star",
          slots: {title: 'hotel_star'},
        },
        {
          dataIndex: 'countryName',
          align: 'left',
          slotName: "country",
          slots: {title: 'country'},
        },
        {
          dataIndex: 'cityName',
          align: 'left',
          slotName: "city",
          slots: {title: 'city'},
        },
        {
          dataIndex: 'distributor',
          align: 'left',
          slotName: "distributor",
          slots: {title: 'distributor'},
          scopedSlots: {customRender: 'distributor'},
        },
        {
          dataIndex: 'distributorHotelId',
          align: 'left',
          slotName: "distributor_hotel_id",
          slots: {title: 'distributor_hotel_id'},
          scopedSlots: {customRender: 'distributorHotelId'},
        },
        {
          dataIndex: 'isonline',
          align: 'center',
          slotName: "sale_status",
          slots: {title: 'sale_status'},
          scopedSlots: {customRender: 'isonline'},
        },
        {
          dataIndex: 'distributorCityName',
          align: 'left',
          slotName: "distributor_city_name",
          slots: {title: 'distributor_city_name'},
          scopedSlots: {customRender: 'distributorCityName'},
        },
        {
          dataIndex: 'pushStatus',
          align: 'left',
          slotName: "push_status",
          slots: {title: 'push_status'},
          scopedSlots: {customRender: 'pushStatus'},
        },
        {
          dataIndex: 'pushResult',
          align: 'left',
          slotName: "push_result",
          slots: {title: 'push_result'},
          scopedSlots: {customRender: 'pushResult'},
        },
        {
          dataIndex: 'pushError',
          align: 'left',
          slotName: "push_error",
          slots: {title: 'push_error'},
        },
        ],
      selectedRows: [],
      selectedRowKeys: [],
      setCityFormVisible: false,
      cityForm: {},
      cityFormRules: {
        distributorCityId: [{required: true, message: ' ', trigger: 'blur'}],
        distributorCityName: [{required: true, message: ' ', trigger: 'blur'}],
      }
    }
  },
  methods: {
    getData() {
      getPublicData('sup_dis_coun').then(res => {
        const {distributors, countryList} = res.data
        this.distributors.push({label: this.$t('distributor'), value: ''})
        distributors.forEach(item => {
          this.distributors.push({label: item, value: item, text: item})
        })
        countryList.forEach(item => {
          this.countryList.push({label: item.countryNameEn, value: item.countryNameEn, text: item.countryNameEn})
        })
      }).catch(error => {
        console.log(error)
      })
    },
    fetchData(){
      this.loading = true
      getHotelList(this.pageIndex, this.pageSize, this.searchParams).then(res => {
        const {rows, total} = res.data.data
        this.data = rows
        this.total = total
        this.loading = false
      }).catch(error => {
        console.log(error)
        this.loading = false
      })
    },
    handleTableChange(pagination) {
      if (this.pageIndex === pagination.current && this.pageSize === pagination.pageSize)
        return

      this.pageIndex = pagination.current;
      this.pageSize = pagination.pageSize;
      this.fetchData()
    },
    handleSearch(e) {
      e.preventDefault();
      this.searchForm.validateFields((error, values) => {
        this.searchParams = values;
        console.log(this.searchParams)
      });
      this.pageIndex = 1
      this.fetchData()
    },
    handleReset() {
      this.searchForm.resetFields();
    },
    openHotel(hotelId){
      this.$openPage('/hotel/detail/' + hotelId, "[" + hotelId + "]")
    },
    openDistributorHotel(distributor, hotelId){
      this.$openPage('/distributor/detail/' + distributor + '/' + hotelId, "[" + distributor + "][" + hotelId + "]")
    },
    filterOption(input, option) {
      return (
          option.componentOptions.children[0].text.toUpperCase().indexOf(input.toUpperCase()) >= 0
      );
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    showSetCityForm(){
      this.setCityFormVisible = true
      this.cityForm = {}
    },
    saveSetCityForm(){
      this.submitLoading = true
      let hotelIds = []
      this.selectedRows.forEach(row => {
        hotelIds.push(row.hotelId)
      })
      setCity({
        distributor: this.selectedRows[0].distributor,
        hotelIds: hotelIds,
        distributorCityId: this.cityForm.distributorCityId,
        distributorCityName: this.cityForm.distributorCityName,
      }).then(res => {
        if (res.data.success) {
          this.$message.success({content: this.$t('submitSuccess')})
          this.submitLoading = false
          this.setCityFormVisible = false
          this.fetchData()
        } else {
          this.$message.error({content: this.$t(res.data.message)})
        }
      }).catch(error => {
        console.log(error)
      })
    },
    saveSetOnline(){
      this.submitLoading = true
      let hotelIds = []
      let distributors = []
      this.selectedRows.forEach(row => {
        distributors.push(row.distributor)
        hotelIds.push(row.hotelId)
      })
      setOnline({
        distributors: distributors,
        hotelIds: hotelIds,
      }).then(res => {
        if (res.data.success) {
          this.$message.success({content: this.$t('submitSuccess')})
          this.submitLoading = false
          this.fetchData()
        } else {
          this.$message.error({content: this.$t(res.data.message)})
        }
      }).catch(error => {
        console.log(error)
      })
    },
    saveSetOffline(){
      this.submitLoading = true
      let hotelIds = []
      let distributors = []
      this.selectedRows.forEach(row => {
        distributors.push(row.distributor)
        hotelIds.push(row.hotelId)
      })
      setOffline({
        distributors: distributors,
        hotelIds: hotelIds,
      }).then(res => {
        if (res.data.success) {
          this.$message.success({content: this.$t('submitSuccess')})
          this.submitLoading = false
          this.fetchData()
        } else {
          this.$message.error({content: this.$t(res.data.message)})
        }
      }).catch(error => {
        console.log(error)
      })
    },
    closeSetCityForm(){
      this.setCityFormVisible = false
    },
  },
  created() {
    this.getData()
    this.pushStatusArr = [
      {label:this.$t("push_status"), value:''},
      {label:this.$t("push_status_arr.0"), value:0},
      {label:this.$t("push_status_arr.10"), value:10},
      {label:this.$t("push_status_arr.20"), value:20},
    ]
    this.pushResultArr = [
      {label:this.$t("push_result"), value:''},
      {label:this.$t("push_result_arr.0"), value:0},
      {label:this.$t("push_result_arr.10"), value:10},
      {label:this.$t("push_result_arr.20"), value:20},
      {label:this.$t("push_result_arr.30"), value:30},
      {label:this.$t("push_result_arr.40"), value:40},
      {label:this.$t("push_result_arr.50"), value:50},
    ]
    this.saleStatusArr = [
      {label:this.$t("sale_status"), value:''},
      {label:this.$t("sale_status_arr.1"), value:1},
      {label:this.$t("sale_status_arr.0"), value:0},
    ]
    this.distributorCityArr = [
      {label:this.$t("distributor_city_name"), value:''},
      {label:this.$t("distributor_city_arr.1"), value:1},
      {label:this.$t("distributor_city_arr.0"), value:0},
    ]
  },
}
</script>

<style scoped>

</style>